package com.hqd.ch03.v11.spel.ast;

import com.hqd.ch03.v11.spel.SpelNode;
import com.hqd.ch03.v11.spel.context.StandardEvaluationContext;
import com.hqd.ch03.v11.spel.standard.ExpressionState;
import org.apache.commons.lang3.ObjectUtils;

/**
 * ast节点抽象类
 */
public abstract class SpelNodeImpl implements SpelNode {
    private final int startPos;

    private final int endPos;
    protected SpelNodeImpl[] children = new SpelNodeImpl[0];
    protected SpelNodeImpl parent;

    public SpelNodeImpl(int startPos, int endPos, SpelNodeImpl... operands) {
        this.startPos = startPos;
        this.endPos = endPos;
        if (!ObjectUtils.isEmpty(operands)) {
            this.children = operands;
            for (SpelNodeImpl operand : operands) {
                operand.parent = this;
            }
        }
    }

    @Override
    public SpelNode getChild(int index) {
        return children[index];
    }

    public Object getValue(StandardEvaluationContext context) {
        return getValue(new ExpressionState(context, context.getRootObj()));
    }

    @Override
    public abstract Object getValue(ExpressionState state);

    @Override
    public int getStartPos() {
        return startPos;
    }

    @Override
    public int getEndPos() {
        return endPos;
    }
}
